<?php


namespace models\Business;


use models\DAO\AlibabaskuModel;
use models\Exception\Business\AlibabaskuException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\AlibabaskuService;
use models\Service\AttributeService;
use Yaf\Registry;

class AlibabaSku
{
    /**
     * 删除商品sku图片
     * @param array $parameters
     * @return bool
     */
    static public function deleteSkuImage($parameters = []) {
        try {
            $res = false;
            if (isset($parameters['url']) && !empty($parameters['url'])) {
                if (strpos($parameters['url'], Registry::get('config')['application']['host']) !== false) {
                    $file = str_replace(Registry::get('config')['application']['host'], APP_PATH . '/public', $parameters['url']);
                } else {
                    $file = $parameters['url'];
                }

                Registry::get('alibaba_log')->err('file: ' . $file);
                Registry::get('alibaba_log')->err('file: ' . json_encode(file_exists($file)));

                if (file_exists($file)) {
//                    Registry::get('alibaba_log')->info('unlink: ' . $file);
                    unlink($file);
                }
            }

            $sql = "UPDATE `alibabasku` SET `sku_image_url` = '0' WHERE `product_id` = '" . $parameters['product_id'] .
                "' AND `sku_image_url` = '" . str_replace(Registry::get('config')['application']['host'], '', $parameters['url']) . "'";
            AlibabaskuModel::getInstance()->getConn()->executeQuery($sql);

            $res = true;
        } catch (\Exception $e) {
            Registry::get('alibaba_log')->err('error: ' . $e->getMessage());
        } finally {
            return $res;
        }
    }

    /**
     * 修改sku图片
     * @param array $parameters
     * @return bool
     */
    static public function editSkuImage($parameters = []) {
        try {
            $res = false;
            $sql = '';
            if (isset($parameters['sku_id']) && isset($parameters['product_id']) && isset($parameters['file']))
                $sql = "UPDATE `alibabasku` SET `sku_image_url` = '" . $parameters['file'] .
                    "' WHERE `sku_id` = '" . $parameters['sku_id'] . "' AND `product_id` = '" . $parameters['product_id'] . "'";

            if (!empty($sql))
                AlibabaskuModel::getInstance()->getConn()->executeQuery($sql);

            $res = true;
        } catch (\Exception $e) {

        } finally {
            return $res;
        }
    }

    /**
     * 修改sku
     * @param array $parameters
     * @return bool
     * @throws AlibabaskuException
     */
    static public function editSku($parameters = []) {
        try {
            $where_str = '';
            $update_arr = [];
            if (isset($parameters['sku_id']) && isset($parameters['product_id']))
                $where_str = '`sku_id` = "' . $parameters['sku_id'] . '" AND `product_id` = "' . $parameters['product_id'] . '"';
                $sql = "UPDATE `alibabasku` SET `sku_image_url` = '" . $parameters['file'] .
                    "' WHERE `sku_id` = '" . $parameters['sku_id'] . "' AND `product_id` = '" . $parameters['product_id'] . "'";

            if (isset($parameters['amount_on_sale']))
                array_push($update_arr, '`amount_on_sale` = "' . $parameters['amount_on_sale'] . '"');

            if (empty($where_str))
                throw new AlibabaskuException(AlibabaskuException::ALIBABASKU_IS_NOT_EXISTS, AlibabaskuException::ALIBABASKU_IS_NOT_EXISTS_NO);

            if (!empty($update_arr)) {
                $sql = "UPDATE `alibabasku` SET " . implode(', ', $update_arr) . " WHERE " . $where_str;
                AlibabaskuModel::getInstance()->getConn()->executeQuery($sql);
                $res = true;
            }

            return $res;
        } catch (\Exception $e) {
            throw new AlibabaskuException(AlibabaskuException::ALIBABASKU_EDIT_FAILURE, AlibabaskuException::ALIBABASKU_EDIT_FAILURE_NO);
        }
    }

    /**
     * 读取sku及其对应的属性
     * @param array $module_list
     * @return array
     */
    static public function getSkuByModules($module_list = []) {
        try {
            $sku_id_arr = $attribute_match_arr = $attribute_arr = [];
            $product_id_arr = array_column($module_list['data'], 'product_id');
            $product_id_arr = array_filter($product_id_arr);

            $sku = AlibabaskuService::getInstance()->getList(1, 999999, 'desc', 'product_id',
                ['groupOp' => 'AND', 'rules' => [[
                    'field' => 'product_id', 'op' => 'in', 'data' => implode(',', $product_id_arr)
                ]]]);

            foreach ($sku['data'] as $idx => $sku_info) {
                if ((strpos($sku_info['sku_image_url'], 'http://') !== false &&
                    strpos($sku_info['sku_image_url'], 'https://') !== false) &&
                    !empty($sku_info['sku_image_url'])
                ) {
                    $sku['data'][$idx]['sku_image_url'] = Registry::get('config')['application']['host'] . $sku_info['sku_image_url'];
                }
            }

            $sku_attribute_id_arr = array_column($sku['data'], 'attribute_id');

            $sku_id_attribute_id_arr = explode(',', implode(',', array_column($sku['data'], 'attribute_id')));

            $attributes = AttributeService::getInstance()->getList(1, count($sku_id_attribute_id_arr),
                'desc', 'id', ['groupOp' => 'AND', 'rules' => [
                    ['field' => 'id', 'op' => 'in', 'data' => implode(',', $sku_id_attribute_id_arr)]
                ]]);

            array_multisort(array_column($attributes['data'], 'attribute_id'), SORT_DESC, $attributes['data']);
            $sku_attributes_match_arr = [];
            foreach ($attributes['data'] as $attribute_idx => $attribute_info) {
                foreach ($sku_attribute_id_arr as $sku_idx => $attribute_id_str) {
                    if (strpos(',' . $attribute_id_str . ',', ',' . $attribute_info['id'] . ',') !== false) {

                        $sku['data'][$sku_idx]['attributes_name'] .= (isset($sku['data'][$sku_idx]['attributes_name']) && !empty($attribute_info['attribute_name']) ? ',' : '') .
                            $attribute_info['attribute_name'];
                        $sku['data'][$sku_idx]['attributes_value'] .= (isset($sku['data'][$sku_idx]['attributes_value']) && !empty($attribute_info['attribute_value']) ? ',' : '') .
                            $attribute_info['attribute_value'];
                        $sku['data'][$sku_idx]['attribute_display_name'] .= (isset($sku['data'][$sku_idx]['attribute_display_name']) && !empty($attribute_info['attribute_display_name']) ? ',' : '') .
                            $attribute_info['attribute_display_name'];

                        $sku['data'][$sku_idx]['attributes'][] = [
                            'id' => $attribute_info['id'],
                            'value' => $attribute_info['attribute_value'],
                            'name' => $attribute_info['attribute_name'],
                            'display_name' => $attribute_info['attribute_display_name'],
                        ];

                        /*if (! in_array($attribute_info['attribute_id'], $attribute_match_arr)) {
                            array_push($attribute_arr, [
                                'id' => $attribute_info['attribute_id'],
                                'value' => $attribute_info['attribute_value'],
                                'name' => $attribute_info['attribute_name'],
                                'display_name' => $attribute_info['attribute_display_name']
                            ]);
                            array_push($attribute_match_arr, $attribute_info['attribute_id']);
                        }*/

                        if (! in_array($sku_idx, $sku_attributes_match_arr)) {
                            $sku_id_arr[$sku['data'][$sku_idx]['product_id']][] = $sku['data'][$sku_idx];
                            array_push($sku_attributes_match_arr, $sku_idx);
                        } else {
                            $key = array_search($sku_idx, $sku_attributes_match_arr);
                            $sku_id_arr[$sku['data'][$sku_idx]['product_id']][$key] = $sku['data'][$sku_idx];
                        }
                    }
                }
            }

//            exit();
        } catch (\Exception $e) {

        } finally {
            foreach ($module_list['data'] as $idx => $module_info) {
                $module_list['data'][$idx]['sku'] = isset($sku_id_arr[$module_info['product_id']]) ? array_values($sku_id_arr[$module_info['product_id']]) : [];
//                $module_list['data'][$idx]['attributes_arr'] = $attribute_arr;
            }

            return $module_list;
        }


    }

    /**
     * 将1688采集的sku入库
     * @param array $product_sku_arr
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function collectSku($product_sku_arr = []) {
        try {
            $sku_id_arr = array_column($product_sku_arr, 'sku_id');
            if (count($sku_id_arr) == 1)
                $sku_exists['data'][] = AlibabaskuService::getInstance()->getOne(implode('', $sku_id_arr));
            else {
                $sku_exists = AlibabaskuService::getInstance()->getList(1, count($sku_id_arr), 'desc', 'sku_id',
                    ['groupOp' => 'AND', 'rules' => [
                        ['field' => 'sku_id', 'op' => 'in', 'data' => implode(",", $sku_id_arr)]]]);
            }

            $batch_insert_arr = $batch_update_arr = [];
            if (! empty($sku_exists['data'])) {
                $exists_sku_id_arr = array_column($sku_exists['data'], 'sku_id');
                foreach ($product_sku_arr as $sku_info) {
                    // 已存在的商品写入更新数据
                    if (in_array($sku_info['sku_id'], $exists_sku_id_arr)) {
                        // 去除商品sku图片
//                        unset($sku_info['sku_image_url']);
                        array_push($batch_update_arr, $sku_info);
                    }
                    // 不存在的商品写入插入数组
                    else
                        array_push($batch_insert_arr, $sku_info);
                }
            } else
                $batch_insert_arr = $product_sku_arr;

            if (!empty($batch_update_arr)) {
                // 更新数组长度大于1，批量插入
                if (count($batch_update_arr) > 1)
                    AlibabaskuService::getInstance()->batchUpdate($batch_update_arr);
                // 更新数组长度等于1，单条更新
                else {
                    $update_arr = array_values($batch_update_arr);
                    $update_arr = $update_arr[0];
                    $sku_id = $update_arr['sku_id'];
                    AlibabaskuService::getInstance()->update($update_arr, $sku_id);
                }
            }

            // 插入数据存在
            if (!empty($batch_insert_arr))
                // 批量插入数据
                AlibabaskuService::getInstance()->batchInsert($batch_insert_arr);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     *根据sku_id获取sku信息
     */
    static public function getSkuByModule($sku_id_arr=[])
    {
        try {
            if (count($sku_id_arr) == 1)
                $sku_list['data'][] = AlibabaskuService::getInstance()->getOne($sku_id_arr[0]);
            else if (count($sku_id_arr) > 1)
                $sku_list = AlibabaskuService::getInstance()->getList(1, count($sku_id_arr), 'desc', 'sku_id',
                    ['groupOp' => 'AND',
                     'rules' => [['field' => 'sku_id', 'op' => 'in', 'data' => implode(',', $sku_id_arr)]]]);

            return $sku_list;
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() == ModelException::DATA_NOT_EXISTS_NO)
                throw new AlibabaskuException(AlibabaskuException::ALIBABASKU_IS_NOT_EXISTS, AlibabaskuException::ALIBABASKU_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

}
